package example.cdx.com.aliplayerdemo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * FastJson的工具类
 */

public class FastJsonUtils {

    public static boolean getBoolean(Object o) {
        String state = o + "";
        state = state.toLowerCase();
        if ("true".equals(state) || "1".equals(state) || "yes".equals(state) || "ok".equals(state)) {
            return true;
        }
        return false;
    }

    public static boolean getBoolean(Map map, String key) {
        return getBoolean(map, key, false);
    }

    public static boolean getBoolean(Map map, String key, boolean defult) {
        if (map != null) {
            Object o = map.get(key);
            if (o instanceof Boolean) {
                return (boolean) o;
            }
        }
        return defult;
    }

    public static String getString(Map map, String key) {
        return getString(map, key, "");
    }

    public static String getString(Map map, String key, String defult) {
        if (key != null) {
            key.trim();
        }
        if (map != null) {
            Object o = map.get(key);
            if (o != null) {
                return String.valueOf(o);
            }
        }

        return defult;
    }

    public static Integer getInteger(Map map, String key) {
        return getInteger(map, key, 0);
    }

    private static Integer getInteger(Map map, String key, Integer defult) {
        if (key != null) {
            key.trim();
        }
        if (map != null) {
            Object o = map.get(key);
            if (o != null) {
                try {
                    //数据错误，会转换成int值的时候出现错误
                    return Integer.parseInt(String.valueOf(o));
                } catch (Exception e) {
                    return defult;
                }
            }
        }

        return defult;
    }

    public static String jsonGetString(String json, String key) {

        return jsonGetString(json, key, "");

    }

    public static String jsonGetString(String json, String key, String def) {
        String par;
        try {
            JSONObject jsonObject = JSON.parseObject(json);
            par = jsonObject.getString(key);
        } catch (Exception e) {
            par = def;
            e.printStackTrace();
        }
        return par;
    }

    public static JSONObject getJsonObject(JSONObject map, String key){
        if (map != null && key != null && key.trim() != null){
            return map.getJSONObject(key);
        }
        return null;
    }
}
